package com.sky.controller.admin;

import com.sky.aop.AutoFill;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.enumeration.OperationType;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.impl.DishServiceImpl;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@Api(tags = "菜品管管理")
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("分类ID查询菜品")
    public Result<List<Dish>> getByIdDish(Long categoryId){
        log.info("[菜品ID] ID:{}",categoryId);
        List<Dish> dishList = dishService.getByIdDish(categoryId);

        return Result.success(dishList);
    }
    @PutMapping
    @ApiOperation("修改菜品信息")
    public Result setDish(@RequestBody DishDTO dishDTO){
        log.info("接受菜品信息{}",dishDTO);
        dishService.updateDishById(dishDTO);
        String keys = "dish_"+dishDTO.getCategoryId();
        clearRedisByCategoryId(keys);
        return Result.success();
    }


    @GetMapping("/{id}")
    @ApiOperation("菜品回显")
    public Result<DishVO> getDish(@PathVariable Long id){
        log.info("[菜品回显]id:{}",id);
        DishVO dishVO = dishService.getDishVO(id);
        return Result.success(dishVO);
    }

    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result deleteDish(@RequestParam List<Long> ids){
        log.info("[批量删除],ids:",ids);
        dishService.deleteDish(ids);
        for (Long id : ids) {
            String keys= "dish_"+id;
            clearRedisByCategoryId(keys);
        }
        return Result.success();
    }

    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dishDTO){
        log.info("[新增菜品] dishDTO：{}",dishDTO);
        dishService.addBatch(dishDTO);
        String keys = "dish_"+dishDTO.getCategoryId();
        clearRedisByCategoryId(keys);

        return Result.success();
    }

    private void clearRedisByCategoryId(String keys) {
        String key =(String) redisTemplate.opsForValue().get(keys);
        if(key != null){
            redisTemplate.delete(key);
        }
    }

    @GetMapping("/page")
    @ApiOperation("分页查询菜品")
    public Result<PageResult> pageDish(DishPageQueryDTO dto){
        log.info("[获取前端信心]，DishPageQueryDTO:{}",dto);
       PageResult pageResult = dishService.byPageDish(dto);
        return Result.success(pageResult);
    }

}
